package utils;

import book.Book;
import book.PairOfUidAndBookId;
import com.bit.utils.FileUtils;

import java.time.LocalDate;

import static constant.Constant.ALL_BOOK_FILE_NAME;
import static constant.Constant.ALL_BORROW_FILE_NAME;

public class AnalyzingBorrowedBook {
    public AnalyzingBorrowedBook() {
    }


    public PairOfUidAndBookId[] loadObject() {
        String content = FileUtils.readFile(ALL_BORROW_FILE_NAME);
        if(content.isEmpty()){
            System.out.println("file content is empty"+ALL_BORROW_FILE_NAME);
            return null;
        }
        String[] lines = content.split("\n");
        PairOfUidAndBookId[] pairOfUidAndBookIds = new PairOfUidAndBookId[lines.length];
        for(int i = 0; i < lines.length; i++){
            pairOfUidAndBookIds[i]=parsePairOfUidAndBookIdsJson(lines[i]);
        }
        return pairOfUidAndBookIds;
    }

    public void storeObject(PairOfUidAndBookId[] pairOfUidAndBookIds){
        int realBookCount = 0;
        for (int i = 0; i < pairOfUidAndBookIds.length; i++) {
            if(pairOfUidAndBookIds[i]!=null){
                realBookCount++;
            }
        }
        StringBuilder stringBuilder=new StringBuilder();
        for (int j = 0; j < realBookCount; j++) {
            stringBuilder.append(pairOfUidAndBookIds[j].toJson());
            if(j!=realBookCount-1){
                stringBuilder.append("\n");
            }
        }

        FileUtils.writeFile(stringBuilder.toString(),ALL_BORROW_FILE_NAME);
    }

    PairOfUidAndBookId parsePairOfUidAndBookIdsJson(String line){
        String[] tmp=line.split(",");
        PairOfUidAndBookId pair=new PairOfUidAndBookId();
        pair.setUserId(Integer.parseInt(tmp[0]));
        pair.setBookId(Integer.parseInt(tmp[1]));
        return pair;
    }

    public static void main(String[] args) {
        PairOfUidAndBookId[] pairOfUidAndBookIds = new PairOfUidAndBookId[3];
        pairOfUidAndBookIds[0] = new PairOfUidAndBookId(1,2);
        pairOfUidAndBookIds[1] = new PairOfUidAndBookId(2,3);
        pairOfUidAndBookIds[2] = new PairOfUidAndBookId(3,4);
        AnalyzingBorrowedBook analyzingBorrowedBook = new AnalyzingBorrowedBook();
        analyzingBorrowedBook.storeObject(pairOfUidAndBookIds);


        pairOfUidAndBookIds=analyzingBorrowedBook.loadObject();

        for (int i = 0; i < pairOfUidAndBookIds.length; i++) {
            System.out.println(pairOfUidAndBookIds[i].toString());
        }
    }
}
